package fr.imag.wifibot.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import org.eclipse.swt.widgets.Display;

public class ListenThread extends Thread{
	private Socket socket;
	private Client c;
	private boolean stop = false;
	
	ListenThread(Client c){
		this.c = c;
	}
	
	public void run(){
		connect();
		try {
			final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while(!stop){
				Display.getDefault().syncExec(new Runnable() {
		               public void run() {
		   				try {
							c.decodeAndPrint(br.readLine());
						} catch (IOException e) {
							stop = true;
						}
		               }
		            });
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void connect(){
		try {
			socket = new Socket(Client.IP,Client.HOST);
			c.setSocket(socket);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Connected : " + socket.isConnected());
	}
}
